
<link rel="stylesheet" href="/layui/lay/modules/ele-tree/eleTree.css" media="all">
<div class="layui-content">
    <!--<div class="layui-page-header">
        <div class="pagewrap">
            <span class="layui-breadcrumb">
              <a href="">首页</a>
              <a href="">用户</a>
              <a><cite>用户组</cite></a>
            </span>
            <h2 class="title">用户组</h2>
        </div>
    </div>-->

    <input type="hidden" id="orgId">
    <input type="hidden" id="orgName">


    <div class="layui-row">
        <div class="layui-col-md2">
            <ul id="userTree"></ul>
        </div>
        <div class="layui-card layui-col-md10">
            <div class="layui-card-body">
                <div class="form-box">
                    <div class="layui-form layui-form-item">
                        <div class="layui-inline">
                            <div class="layui-form-mid">姓名:</div>
                            <div class="layui-input-inline" style="width: 100px;">
                              <input id="userName" type="text" autocomplete="off" class="layui-input">
                            </div>
                            <div class="layui-form-mid">邮箱:</div>
                            <div class="layui-input-inline" style="width: 100px;">
                              <input id="userEmail" type="text" autocomplete="off" class="layui-input">
                            </div>
                            <button id="userSearch" class="layui-btn layui-btn-blue">查询</button>
                            <!--<button class="layui-btn layui-btn-primary">重置</button>-->
                        </div>
                    </div>
                    <button id="userAdd" class="layui-btn layui-btn-blue"><i class="layui-icon">&#xe654;</i>新增</button>
                    <button id="userDelete" class="layui-btn layui-btn-danger"><i class="layui-icon">&#xe640;</i>批量删除</button>
                    <table id="userTable" lay-filter="userTable"></table>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/html" id="userTableBar">
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="assignRole">分配角色</a>
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script type="text/html" id="regionTemplate">
    {{#  if(d.region == 0){ }}
        <span>北京</span>
    {{#  } else if(d.region == 1) { }}
        <span>上海</span>
    {{#  } else if(d.region == 2) { }}
        <span>广州</span>
    {{#  } else if(d.region == 3) { }}
        <span>深圳</span>
    {{#  } else if(d.region == 4) { }}
        <span>西安</span>
    {{#  } else { }}
        <span>未知</span>
    {{#  } }}
</script>


<script>

    $(function(){
        var element = layui.element;
        var table = layui.table;
        var form = layui.form;


        $("#userAdd").click(function () {
            layui.use(['home'], function(){
                var tabs = layui.home.tabs;
                var navItems = layui.home.navItems;

                var $this = $(this), url = 'user/form.html',
                    title = '添加用户';
                if( url && url!=='javascript:;' ){
                    if(tabs.is(url)){
                        tabs.change(url);
                    } else {
                        navItems.push($this);
                        tabs.add(title, url);
                    }
                }
                $this.closest('li.layui-nav-item')
                    .addClass('layui-nav-itemed')
                    .siblings()
                    .removeClass('layui-nav-itemed');
            });
        });

        $("#userDelete").click(function () {
            var checkStatus = table.checkStatus('userTable'); //idTest 即为基础参数 id 对应的值
            var data = checkStatus.data;
            var len = data.length;
            if(len == 0){
                return;
            }

            layer.confirm('确认删除选择数据吗?',{ icon: 0}, function(index) {
                var idArray = new Array();
                for (var i = 0; i < data.length; i++) {
                    idArray.push(data[i].id);
                }

                $.post('user/removeUsers', {ids: idArray}, function (data) {
                    layer.msg('删除成功');
                    table.reload('userTable', {
                        page: 1
                    });
                })
            });
        });


        $("#userSearch").click(function () {
            var userName = $("#userName").val();
            var userEmail = $("#userEmail").val();
            table.reload('userTable',{
                where:{
                    name:userName,
                    email:userEmail
                },
                page:1
            }); //表格重载
        });

        //展示已知数据
        table.render({
            elem: '#userTable'
            ,url: 'user/getUserList' //数据接口
            ,cols: [[ //标题栏
                {type:'checkbox'}
                ,{field: 'id', title: 'id', width: 80, sort: true}
                ,{field: 'loginName', title: '用户名', width: 150}
                ,{field: 'name', title: '姓名', width: 150}
                ,{field: 'orgname', title: '所属机构', width: 100}
                ,{field: 'email', title: '邮箱', minWidth: 80}
                ,{field: 'phone', title: '电话', minWidth: 80}
                ,{field: 'region', title: '地域', width: 100,templet: '#regionTemplate'}
                ,{field: 'regionText', title: '地域3', width: 100}
                ,{field: 'qqnumber', title: 'QQ号码', width: 150}
                ,{field: 'createDate', title: '创建时间', width: 150}
                ,{fixed: 'right', title:'操作', toolbar: '#userTableBar', width:200}
            ]]
            ,response: {
                //statusName: 'status' //规定数据状态的字段名称，默认：code
                //,statusCode: 200 //规定成功的状态码，默认：0
                countName: 'total' //规定数据总数的字段名称，默认：count
                ,dataName: 'list' //规定数据列表的字段名称，默认：data
            }
        /*,data: [{
            "id": "10001"
            ,"username": "杜甫"
            ,"email": "xianxin@layui.com"
            ,"sex": "男"
            ,"city": "浙江杭州"
            ,"sign": "人生恰似一场修行"
            ,"experience": "116"
            ,"ip": "192.168.0.8"
            ,"logins": "108"
            ,"joinTime": "2016-10-14"
        }, {
            "id": "10002"
            ,"username": "李白"
            ,"email": "xianxin@layui.com"
            ,"sex": "男"
            ,"city": "浙江杭州"
            ,"sign": "人生恰似一场修行"
            ,"experience": "12"
            ,"ip": "192.168.0.8"
            ,"logins": "106"
            ,"joinTime": "2016-10-14"
            ,"LAY_CHECKED": true
        }, {
            "id": "10003"
            ,"username": "王勃"
            ,"email": "xianxin@layui.com"
            ,"sex": "男"
            ,"city": "浙江杭州"
            ,"sign": "人生恰似一场修行"
            ,"experience": "65"
            ,"ip": "192.168.0.8"
            ,"logins": "106"
            ,"joinTime": "2016-10-14"
        }, {
            "id": "10004"
            ,"username": "贤心"
            ,"email": "xianxin@layui.com"
            ,"sex": "男"
            ,"city": "浙江杭州"
            ,"sign": "人生恰似一场修行"
            ,"experience": "666"
            ,"ip": "192.168.0.8"
            ,"logins": "106"
            ,"joinTime": "2016-10-14"
        }, {
            "id": "10005"
            ,"username": "贤心"
            ,"email": "xianxin@layui.com"
            ,"sex": "男"
            ,"city": "浙江杭州"
            ,"sign": "人生恰似一场修行"
            ,"experience": "86"
            ,"ip": "192.168.0.8"
            ,"logins": "106"
            ,"joinTime": "2016-10-14"
        }, {
            "id": "10006"
            ,"username": "贤心"
            ,"email": "xianxin@layui.com"
            ,"sex": "男"
            ,"city": "浙江杭州"
            ,"sign": "人生恰似一场修行"
            ,"experience": "12"
            ,"ip": "192.168.0.8"
            ,"logins": "106"
            ,"joinTime": "2016-10-14"
        }, {
            "id": "10007"
            ,"username": "贤心"
            ,"email": "xianxin@layui.com"
            ,"sex": "男"
            ,"city": "浙江杭州"
            ,"sign": "人生恰似一场修行"
            ,"experience": "16"
            ,"ip": "192.168.0.8"
            ,"logins": "106"
            ,"joinTime": "2016-10-14"
        }, {
            "id": "10008"
            ,"username": "贤心"
            ,"email": "xianxin@layui.com"
            ,"sex": "男"
            ,"city": "浙江杭州"
            ,"sign": "人生恰似一场修行"
            ,"experience": "106"
            ,"ip": "192.168.0.8"
            ,"logins": "106"
            ,"joinTime": "2016-10-14"
        }]*/
            ,skin: 'line' //表格风格
            ,page: true //是否显示分页
            ,limits: [10, 20, 50]
            ,limit: 10 //每页默认显示的数量
        });


        function loadTree(){
            $("#userTree").html(""); // 清空防止重复
            $.get('org/getOrgListTree',{},function(data){
                layui.tree({
                    elem: '#userTree' //传入元素选择器
                    ,nodes: data/*[{ //节点
                    id:1,
                    name: '父节点1'
                    ,children: [{
                        id:11,
                        name: '子节点11'
                    },{
                        id:12,
                        name: '子节点12'
                    }]
                },{
                    id:2,
                    name: '父节点2（可以点左侧箭头，也可以双击标题）'
                    ,children: [{
                        id:21,
                        name: '子节点21'
                        ,children: [{
                            id:211,
                            name: '子节点211'
                        }]
                    }]
                }]*/
                    ,click: function(node){
                        $("#orgId").val(node.id);
                        $("#orgName").val(node.name);

                        table.reload('userTable', {
                            where:{
                                orgname:node.name
                            },
                            page: 1
                        });
                    }
                });
            },'json');
        }


        // 加载树
        loadTree();


        //监听行工具事件
        table.on('tool(userTable)', function(obj){
            var data = obj.data;
            //console.log(obj)
            if(obj.event === 'del'){
                layer.confirm('确认删除选择数据吗?',{ icon: 0}, function(index){
                    $.post('user/removeUser',{id:data.id},function(data){
                        layer.msg('删除成功');
                        layer.close(index);
                        table.reload('userTable',{
                            page:1
                        });
                    })
                });


            } else if(obj.event === 'edit'){
                $.get('user/form.html',function(html){
                    var index = layer.open({
                        type: 1
                        ,title: '用户添加'
                        ,area: ['700px', '530px']
                        ,shade: 0
                        ,maxmin: true
                        ,content: html
                        //,btn: ['保存', '取消']
                        ,yes: function(){
                            $(that).click();
                        }
                        ,btn2: function(){
                            layer.close(index);
                        }
                    });

                    $("#layerIndex").val(index);
                    // 表单赋值
                    var form = layui.form;
                    form.val("user-form", data);

                });

            } else if(obj.event === 'assignRole'){
                var tree;
                var index = layer.open({
                    type: 1
                    ,title: '角色分配'
                    ,area: ['400px', '300px']
                    ,shade: 0
                    ,maxmin: true
                    ,content: '<ul id="roleTree"></ul>'
                    ,btn: ['保存', '取消']
                    ,yes: function(){
                        var roles = tree.getChecked(false, true);
                        var roleIdArray = new Array();
                        for(var i = 0; i< roles.length; i++){
                            roleIdArray.push(roles[i].id);
                        }
                        $.post('user/addRole',{userId:data.id,roleIds:roleIdArray},function(){
                            layer.msg('设置成功');
                            layer.close(index);
                        });
                    }
                    ,btn2: function(){
                        layer.close(index);
                    }
                });

                layui.extend({
                    eleTree: 'ele-tree/eleTree'
                }).use(['eleTree'], function () {
                    tree = layui.eleTree.render({
                        elem: '#roleTree',
                        url: 'role/getRoleList',
                        showCheckbox: true,
                        request: {
                            name: "name",
                            key: "id",
                            children: "children",
                            checked: "checked",
                            disabled: "disabled",
                            isLeaf: "isLeaf"
                        },
                        response: {
                            statusName: "code",
                            statusCode: 0,
                            dataName: "list"
                        },
                        done:function(){
                            $.get('user/getRoleByUserId?userId=' + data.id,{},function(data){
                                var idArray = new Array();
                                for(var i = 0 ; i< data.length;i++){
                                    idArray.push(data[i].roleId);
                                }
                                tree.setChecked(idArray,true);
                            },'json');

                        }
                    });
                });
            }
        });

    });
</script>